<?php

namespace app\common\service\product;

use app\common\model\product\Product;
use app\common\model\product\ProductSku;
use app\common\library\helper;


/**
 * 商品服务类,公共处理方法
 */
class BaseProductService
{
    /**
     * 商品多规格信息
     */
    public static function getSpecData($model = null)
    {
        // 商品sku数据
        if (!is_null($model) && $model['spec_type'] == 20) {
            return $model->getManySpecData($model['spec_rel'], $model['sku']);
        }
        return null;
    }

    /**商品价格 */
    public static function getProductPrice($product_id, $num = 1, $spec_sku_id = "", $user = null)
    {
        $product = Product::find($product_id);
        $price = $product['product_price'];
        if ($spec_sku_id) {
            $sku = ProductSku::where(['product_id' => $product_id, 'spec_sku_id' => $spec_sku_id])->find();
            if ($sku) {
                $price = $sku['product_price'];
            }
        }
        //会员折扣
        if ($user && $user['grade'] && $product['is_enable_grade']) {
            $alone_grade_type = 10;
            // 商品单独设置了会员折扣
            if ($product['is_alone_grade'] && isset($product['alone_grade_equity'][$user['grade_id']])) {
                if ($product['alone_grade_type'] == 10) {
                    // 折扣比例
                    $discountRatio = helper::bcdiv($product['alone_grade_equity'][$user['grade_id']], 100);
                } else {
                    $alone_grade_type = 20;
                    $discountRatio = helper::bcdiv($product['alone_grade_equity'][$user['grade_id']], $product['product_price'], 2);
                }
            } else {
                // 折扣比例
                $discountRatio = helper::bcdiv($user['grade']['equity'] ?? 100, 100);
            }
            if ($discountRatio < 1) {
                // 会员折扣后的商品总金额
                if ($alone_grade_type == 20) {
                    // 固定金额
                    $price = $product['alone_grade_equity'][$user['grade_id']];
                } else {
                    $price = helper::number2(helper::bcmul($price, $discountRatio), true);
                }
            }
        }
        $total_price = helper::number2(helper::bcmul($price, $num), true);
        return [
            'product_price' => $price,
            'total_price' => $total_price,
        ];
    }
}